﻿using DingTalk.Models;
using Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DingTalkByHttp
{
    class Program
    {
        static void Main(string[] args)
        {
            DingTalkApi dingTalkApi = DingTalkApi.GetInstance();
            string userId = dingTalkApi.GetUserIDByMobile("17345060826");
            if (string.IsNullOrWhiteSpace(userId))
            {
                throw new Exception("获取钉钉用户ID失败");
            }
            //获取用户详情
            var userInfo = dingTalkApi.GetUserInfoByUserID(userId);
            if (userInfo == null)
            {
                throw new Exception("获取钉钉用户详情失败");
            }
            //获取钉盘空间ID
            string spaceId = dingTalkApi.GetAttachSpaceID(userId);
            if (string.IsNullOrWhiteSpace(spaceId))
            {
                throw new Exception("获取钉盘空间失败");
            }
            //创建文件夹获取UUID
            string uuId = dingTalkApi.CreateFolder(userInfo.unionid, spaceId, userId);
            if (string.IsNullOrWhiteSpace(uuId))
            {
                throw new Exception("创建文件夹失败");
            }
            #region 上传临时素材
            List<DingFileInfoModel> dingFileInfos = new List<DingFileInfoModel>();
            //文件夹授权
            bool auth = dingTalkApi.AddFolderPermission(uuId, userInfo.unionid, userId);
            if (auth)
            {
                var uploadInfo = dingTalkApi.GetFileUploadInfo(userInfo.unionid, spaceId, uuId);
                //上传文件
                var upRes = DingTalkApi.HttpRequest(uploadInfo.headerSignatureInfo.resourceUrls[0], @"D:\2.png", uploadInfo.headerSignatureInfo.headers,2);
                DingFileInfoModel dingFileInfo = dingTalkApi.commitFile(uuId, userInfo.unionid, uploadInfo.uploadKey, "2.png");
                dingFileInfos.Add(dingFileInfo);
            }
            #endregion
            string payApplyTemplateId = "PROC-13F2A3E1-26A8-42C8-98A0-D11F951C9FB5";
            //获取审批表单结构
            var formComponents = dingTalkApi.QuerySchemaByProcessCode(payApplyTemplateId);
            //发起审批
            string spNo = dingTalkApi.CreatePayApplyProcess(userInfo, payApplyTemplateId, formComponents, dingFileInfos);
        }
    }
}
